#!/usr/bin/python

import socket
import getpass
import commands
import sys
import telnetlib
import time

from types import *

username="whq"
#password = getpass.getpass()
password="whq"

if len(sys.argv)!=2:
  print "Usage: %s IP Address you want " % sys.argv[0]
  sys.exit(1)


cmd='remoteCommand | grep %s' %(sys.argv[1])

logstr='/tmp/checkIP.log_'+time.strftime("%H:%M:%S", time.localtime())

f=file(logstr, 'w')

server_list=['1.1.1.1','1.1.1.2']

log_str="\n=======The detailed log is in "+logstr+"======="
print log_str

for x in server_list:

  begin_str="\n======Start to check on server " + x
  print begin_str
  f.write(begin_str)

  tn=telnetlib.Telnet()
  try:
     tn.open(x,23)
  except socket.error:
     print ( '----whq, hit socket error-------------------------------' )
     continue

  tn.read_until("login: ")
  tn.write(username + "\n")
  if password:
      tn.read_until("Password: ")
      tn.write(password + "\n")

  seperator='\r\n'
  unix_seperator='\n'

  try:
     response=tn.read_until(">")
  except EOFError:
     print ( '----whq, hit EOFError, username/passwd doesn\'t match----' )
     continue

  update_response=response.replace(seperator,unix_seperator)
  f.write(update_response)

  tn.write(cmd + "\n")
  f.write(cmd)
  f.write("\n")
 
  try:
     response=tn.read_until(">")
  except EOFError:
     print ( '----whq, hit EOFError, username/passwd doesn\'t match----' )
     continue

  update_response=response.replace(seperator,unix_seperator)
  f.write(update_response)

  equipList=response.split(seperator)
  list_len=len(equipList)
  
  if type(sys.argv[1]) is StringType:
  	str2=sys.argv[1]
  
  for i in range(list_len-1):
      finalList=equipList[i].split(',')
      if type(finalList[2]) is StringType:
      	str1=finalList[2] 

      if str1 == str2:
        hit_str="\nThis IP is on server: " + x
        print hit_str
        name_str="Other INFO: "+finalList[1]
        print name_str
        ip_str="IP: "+finalList[2]
        print ip_str
 
  tn.write("exit\n")
  
  response=tn.read_all()
  update_response=response.replace(seperator,unix_seperator)
  f.write(update_response)

  
  


